<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageToos :show-before="false">
        <template #before>
          12313
        </template>
        <template #after>
          <el-button type="danger" @click="saverExcel">导出</el-button>
          <el-button type="primary" @click="$router.push('/import')">导入</el-button>
          <el-button type="primary" @click="showDialog=true">+ 员工添加</el-button>
        </template>
      </PageToos>
      <el-card v-loading="loading">
        <el-table border :data="tableData">
          <el-table-column label="序号" sortable="" type="index">
            <template #default="{$index}">
              {{ (page.page-1)*page.size+$index+1 }}
            </template>
          </el-table-column>
          <el-table-column label="头像" width="200" sortable="" prop="username">
            <template #default="{row}">
              <img v-imgerr="require('@/assets/common/head.jpg')" :src="row.staffPhoto" class="staffPhoto" alt="" @click="CreateQrCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" :formatter="formattEremployees" sortable="" prop="formOfEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry|formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template #default="{row}">
              <el-switch
                :value="row.enableState===1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push({path:'employees/detail/'+row.id})">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="role(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployees(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="total,prev, pager, next"
            :page-size="page.size"
            :current-page="page.page"
            :total="total"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
      <el-dialog title="二维码" :visible.sync="showQRcode">
        <el-row type="flex" justify="center">
          <canvas ref="mycode" />
        </el-row>
      </el-dialog>
      <addemployee :show-dialog.sync="showDialog" :user-id="userId" />
      <assigeRole ref="rows" :show-role-dialog.sync="showassigeRole" />
    </div>
  </div>
</template>

<script>
import { employeeList, Delemployee } from '@/api/employee'
// 引入枚举数据
import employees from '@/api/constant/employees'
import { formatDate } from '@/api/filters'
import addemployee from '@/views/employees/components/addemployee.vue'
import QRCode from 'qrcode'
import assigeRole from '@/views/employees/components/assign-role.vue'
export default {
  filters: {
    // formDate(olevalue) {
    //   return olevalue.split('T')[0]
    // }
  },
  components: {
    addemployee, assigeRole
  },
  data() {
    return {
      userId: '',
      showQRcode: false,
      loading: false,
      showDialog: false,
      showassigeRole: false,
      tableData: [],
      page: {
        page: 1,
        size: 5
      },
      total: 10
    }
  },
  created() {
    this.employeeList()
  },
  methods: {
    role(id) {
      this.$refs.rows.rows(id)
      this.showassigeRole = true
    },
    CreateQrCode(url) {
      this.showQRcode = true
      this.$nextTick(() => {
        QRCode.toCanvas(this.$refs.mycode, url, {
          // 额外可选参数, 控制二维码颜色
          width: 200,
          color: {
            dark: '#5081fc'
          }
        })
      })
    },
    async employeeList() {
      this.loading = true
      const { rows, total } = await employeeList(this.page)
      this.tableData = rows
      console.log(this.tableData)
      this.total = total
      this.loading = false
    },
    changePage(newPage) {
      this.page.page = newPage
      this.employeeList()
    },
    async delEmployees(id) {
      try {
        await this.$confirm('确定要删除吗？')
        await Delemployee(id)
        if (this.tableData.length === 1 && this.page.page !== 1) {
          this.page.page--
        }
        this.employeeList()
      } catch (error) {
        console.log(error)
      }
    },
    formattEremployees(row, column, cellValue) {
      // 枚举
      const Judge = employees.hireType.find(item => item.id === cellValue)
      return Judge ? Judge.value : '未知类型'
    },
    async  saverExcel() {
      // 按需导入
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      const { rows } = await employeeList({ page: 1, size: this.total })
      const userRelations = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // Object.keys()会组成数据
      const header = Object.keys(userRelations)
      const data = []
      rows.forEach(item => {
        let value, enkey
        const arr = []
        for (const key in userRelations) {
          enkey = userRelations[key]
          value = item[enkey]
          if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
            value = formatDate(item[enkey])
          }
          if (enkey === 'formOfEmployment') {
            value = employees.hireType.find(item => item.id === Number(value))
            value = value ? value.value : '未知类型'
          }
          arr.push(value)
        }
        data.push(arr)
      })
      export_json_to_excel({ header, data })
    }
  }
}
</script>

<style lang="scss" scoped>
.staffPhoto{
  width: 100%;
  height: 100%;
 object-fit: cover;
 border-radius: 15px;
}
</style>
